import { createRouter, createWebHistory } from 'vue-router'
import DefaultLayout from '../layouts/DefaultLayout.vue'
import AuthLayout from '../layouts/AuthLayout.vue'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/auth/login'  // 直接重定向到登录页面
  },
  {
    path: '/auth',
    component: AuthLayout,
    children: [
      {
        path: 'login',
        name: 'login',
        component: () => import('../views/auth/LoginView.vue'),
        meta: { title: '登录' }
      },
      {
        path: 'register',
        name: 'register',
        component: () => import('../views/auth/RegisterView.vue'),
        meta: { title: '注册' }
      },
      {
        path: 'forgot-password',
        name: 'forgotPassword',
        component: () => import('../views/auth/ForgotPasswordView.vue'),
        meta: { title: '忘记密码' }
      }
    ]
  },
  {
    path: '/',
    component: DefaultLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'dashboard',
        component: () => import('../views/dashboard/DashboardView.vue'),
        meta: { title: '仪表盘', icon: 'el-icon-monitor', requiresAuth: true }
      },
      // 基础数据管理路由
      {
        path: 'base-data',
        name: 'baseData',
        component: () => import('../views/baseData/BaseDataView.vue'),
        meta: { title: '基础数据', icon: 'el-icon-folder', requiresAuth: true },
        children: [
          {
            path: 'enterprise',
            name: 'enterprise',
            component: () => import('../views/baseData/EnterpriseView.vue'),
            meta: { title: '企业/承运商管理', requiresAuth: true }
          },
          {
            path: 'vehicle',
            name: 'vehicle',
            component: () => import('../views/baseData/VehicleView.vue'),
            meta: { title: '车辆档案', requiresAuth: true }
          },
          {
            path: 'route',
            name: 'route',
            component: () => import('../views/baseData/RouteView.vue'),
            meta: { title: '路线地图', requiresAuth: true }
          },
          {
            path: 'pricing',
            name: 'pricing',
            component: () => import('../views/baseData/PricingView.vue'),
            meta: { title: '计价模型', requiresAuth: true }
          },
          {
            path: 'driver',
            name: 'driver',
            component: () => import('../views/baseData/DriverView.vue'),
            meta: { title: '驾驶员档案', requiresAuth: true }
          }
        ]
      },
      // 订单管理路由
      {
        path: 'orders',
        name: 'orders',
        component: () => import('../views/orders/OrderView.vue'),
        meta: { title: '订单管理', icon: 'el-icon-document', requiresAuth: true },
        children: [
          {
            path: 'list',
            name: 'orderList',
            component: () => import('../views/orders/OrderListView.vue'),
            meta: { title: '订单列表', requiresAuth: true }
          },
          {
            path: 'create',
            name: 'orderCreate',
            component: () => import('../views/orders/OrderCreateView.vue'),
            meta: { title: '创建订单', requiresAuth: true }
          },
          {
            path: 'emergency',
            name: 'emergencyOrders',
            component: () => import('../views/orders/EmergencyOrderView.vue'),
            meta: { title: '紧急订单处理', requiresAuth: true }
          }
        ]
      },
      // 运输管理路由
      {
        path: 'transport',
        name: 'transport',
        component: () => import('../views/transport/TransportView.vue'),
        meta: { title: '运输管理', icon: 'el-icon-truck', requiresAuth: true },
        children: [
          {
            path: 'plan',
            name: 'transportPlan',
            component: () => import('../views/transport/TransportPlanView.vue'),
            meta: { title: '运输计划', requiresAuth: true }
          },
          {
            path: 'plan/detail/:id',
            name: 'transportPlanDetail',
            component: () => import('../views/transport/TransportPlanDetailView.vue'),
            meta: { title: '计划详情', requiresAuth: true },
            props: true
          },
          {
            path: 'monitor',
            name: 'transportMonitor',
            component: () => import('../views/transport/TransportMonitorView.vue'),
            meta: { title: '运输监控', requiresAuth: true }
          },
          {
            path: 'analytics',
            name: 'transportAnalytics',
            component: () => import('../views/transport/TransportAnalyticsView.vue'),
            meta: { title: '统计分析', requiresAuth: true }
          }
        ]
      },
      // 运输计划路由
      {
        path: 'planning',
        name: 'planning',
        component: () => import('../views/planning/PlanningView.vue'),
        meta: { title: '运输计划', icon: 'el-icon-map-location', requiresAuth: true },
        children: [
          {
            path: 'route-optimization',
            name: 'routeOptimization',
            component: () => import('../views/planning/RouteOptimizationView.vue'),
            meta: { title: '路径优化', requiresAuth: true }
          },
          {
            path: 'load-optimization',
            name: 'loadOptimization',
            component: () => import('../views/planning/LoadOptimizationView.vue'),
            meta: { title: '装载优化', requiresAuth: true }
          }
        ]
      },
      // 调度执行路由
      {
        path: 'dispatch',
        name: 'dispatch',
        component: () => import('../views/dispatch/DispatchView.vue'),
        meta: { title: '调度执行', icon: 'el-icon-truck', requiresAuth: true },
        children: [
          {
            path: 'tracking',
            name: 'tracking',
            component: () => import('../views/dispatch/TrackingView.vue'),
            meta: { title: '实时跟踪', requiresAuth: true }
          },
          {
            path: 'exceptions',
            name: 'exceptions',
            component: () => import('../views/dispatch/ExceptionsView.vue'),
            meta: { title: '异常管理', requiresAuth: true }
          }
        ]
      },
      // 费用结算路由
      {
        path: 'billing',
        name: 'billing',
        component: () => import('../views/billing/BillingView.vue'),
        meta: { title: '费用结算', icon: 'el-icon-money', requiresAuth: true },
        children: [
          {
            path: 'documents',
            name: 'documents',
            component: () => import('../views/billing/DocumentsView.vue'),
            meta: { title: '单据处理', requiresAuth: true }
          },
          {
            path: 'accounting',
            name: 'accounting',
            component: () => import('../views/billing/AccountingView.vue'),
            meta: { title: '会计处理', requiresAuth: true }
          }
        ]
      },
      // 报表路由
      {
        path: 'reports',
        name: 'reports',
        component: () => import('../views/reports/ReportsView.vue'),
        meta: { title: '报表分析', icon: 'el-icon-data-analysis', requiresAuth: true },
        children: [
          {
            path: 'kpi',
            name: 'kpi',
            component: () => import('../views/reports/KpiView.vue'),
            meta: { title: 'KPI仪表盘', requiresAuth: true }
          },
          {
            path: 'business-intelligence',
            name: 'businessIntelligence',
            component: () => import('../views/reports/BusinessIntelligenceView.vue'),
            meta: { title: '商业智能', requiresAuth: true }
          }
        ]
      },
      // 系统管理路由
      {
        path: 'system',
        name: 'system',
        component: () => import('../views/system/SystemView.vue'),
        meta: { title: '系统管理', icon: 'el-icon-setting', requiresAuth: true },
        children: [
          {
            path: 'user',
            name: 'systemUser',
            component: () => import('../views/system/UserManageView.vue'),
            meta: { title: '用户管理', requiresAuth: true }
          },
          {
            path: 'role',
            name: 'systemRole',
            component: () => import('../views/system/RoleView.vue'),
            meta: { title: '角色管理', requiresAuth: true }
          },
          {
            path: 'department',
            name: 'systemDepartment',
            component: () => import('../views/system/DepartmentView.vue'),
            meta: { title: '部门管理', requiresAuth: true }
          },
          {
            path: 'position',
            name: 'systemPosition',
            component: () => import('../views/system/PositionView.vue'),
            meta: { title: '职位管理', requiresAuth: true }
          },
          {
            path: 'menu',
            name: 'systemMenu',
            component: () => import('../views/system/MenuView.vue'),
            meta: { title: '菜单管理', requiresAuth: true }
          }
        ]
      },
      // 用户相关路由
      {
        path: 'user',
        name: 'user',
        meta: { requiresAuth: true },
        children: [
          {
            path: 'profile',
            name: 'userProfile',
            component: () => import('../views/user/ProfileView.vue'),
            meta: { title: '个人资料', requiresAuth: true }
          },
          {
            path: 'password',
            name: 'userPassword',
            component: () => import('../views/user/PasswordView.vue'),
            meta: { title: '修改密码', requiresAuth: true }
          }
        ]
      }
    ]
  },
  // 错误页面
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('../views/NotFoundView.vue'),
    meta: { title: '页面未找到' }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/NotFoundView.vue'),
    meta: { title: '页面未找到' }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 检查用户是否有权限访问路由
const hasPermission = (to) => {
  // 从localStorage获取用户信息
  const userInfoStr = localStorage.getItem('userInfo')
  if (!userInfoStr) {
    return false
  }
  
  try {
    const userInfo = JSON.parse(userInfoStr)
    const roles = userInfo.roles || []
    const menus = userInfo.menus || []
    
    // 如果用户有超级管理员角色，允许访问所有页面
    if (roles.includes('ROLE_ADMIN') || roles.includes('ADMIN') || userInfo.username === 'admin') {
      return true
    }
    
    // 如果没有菜单数据，默认不允许访问
    if (!menus || menus.length === 0) {
      return false
    }
    
    // 检查当前路由是否在用户的菜单权限中
    // 这里假设后端返回的菜单数据中包含path字段
    const hasMenu = menus.some(menu => {
      if (menu.path === to.path) {
        return true
      }
      
      // 检查子菜单
      if (menu.children && menu.children.length > 0) {
        return menu.children.some(child => child.path === to.path)
      }
      
      return false
    })
    
    return hasMenu
  } catch (error) {
    console.error('解析用户权限数据出错:', error)
    return false
  }
}

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - TMS系统` : 'TMS系统'
  
  // 如果路由不存在，重定向到登录页面
  if (to.matched.length === 0) {
    next('/auth/login')
    return
  }
  
  // 如果访问的是登录相关页面，直接放行
  if (to.path.startsWith('/auth') || to.path === '/404') {
    next()
    return
  }
  
  // 检查是否需要登录
  const isAuthenticated = !!localStorage.getItem('token')
  
  if (!isAuthenticated) {
    // 未登录，重定向到登录页
    next({
      path: '/auth/login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 已登录，检查权限
  const userInfoStr = localStorage.getItem('userInfo')
  if (!userInfoStr) {
    // 如果没有用户信息，重新获取
    import('@/api/auth').then(module => {
      module.getUserInfo().then(res => {
        if (res && res.data) {
          const { username, roles, menus } = res.data
          
          // 保存用户信息
          const userInfo = {
            username,
            roles,
            permissions: roles,
            menus
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          
          // 检查权限
          if (hasPermission(to)) {
            next()
          } else {
            next({ path: '/dashboard' })
          }
        } else {
          console.error('获取用户信息失败: 响应数据格式不正确')
          localStorage.removeItem('token')
          next({
            path: '/auth/login',
            query: { redirect: to.fullPath }
          })
        }
      }).catch(error => {
        // 获取用户信息失败，清除token并重定向到登录页
        console.error('获取用户信息失败:', error)
        localStorage.removeItem('token')
        next({
          path: '/auth/login',
          query: { redirect: to.fullPath }
        })
      })
    }).catch(error => {
      console.error('加载auth模块失败:', error)
      next({
        path: '/auth/login',
        query: { redirect: to.fullPath }
      })
    })
  } else {
    try {
      // 检查权限
      if (hasPermission(to)) {
        next()
      } else {
        next({ path: '/dashboard' })
      }
    } catch (error) {
      console.error('权限检查失败:', error)
      next({ path: '/dashboard' })
    }
  }
})

export default router
